<template>
  <div>
    <n-card :bordered="false" class="fromCard">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        :Toption="orgStatus"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="tableCard">
      <BasicTable
        :bordered="false"
        :columns="columns"
        :request="loadDataTable"
        ref="actionRef"
        :row-key="(row) => row.id"
        :actionColumn="actionColumn"
        :scroll-x="500"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addInfo" :disabled='!authority.includes("org_add")'>
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            新建
          </n-button>
        </template>
      </BasicTable>
    </n-card>
    <!-- 添加操作 -->
    <n-modal :show="addModal">
      <n-card style="width: 1000px" title="新增机构" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          :model="addRoleMsg"
          :rules="addOrg"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28">
            <n-gi span="1" style="margin-bottom: 16px">
              <n-form-item :span="1" label="机构名称" path="orgName">
                <n-input placeholder="机构名称" v-model:value="addRoleMsg.orgName"  maxlength="255"/>
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="机构代码" path="code">
                <n-input placeholder="机构代码" v-model:value="addRoleMsg.code" maxlength="20"/>
              </n-form-item>
            </n-gi>
            <n-gi span="1" style="margin-bottom: 20px">
              <n-form-item :span="1" label="父级机构" path="parentName">
                <n-select
                  placeholder="选择父级机构"
                  :options="parentNameOptions"
                  v-model:value="addRoleMsg.parentName"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="状态" path="status">
                <n-select
                  placeholder="选择父级机构"
                  :options="statusOptions"
                  v-model:value="addRoleMsg.status"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="描述" path="remark">
                <n-input placeholder="机构描述" v-model:value="addRoleMsg.remark"  maxlength="100"/>
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button type="info" :loading="formBtnLoading" @click="addFrom">确定</n-button>
            <n-button @click="() => (addModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 编辑操作 -->
    <n-modal :show="editModal">
      <n-card style="width: 1000px" title="机构编辑" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          size="medium"
          ref="formRef"
          label-placement="left"
          label-align="left"
          :model="setOrg"
        >
          <n-grid :cols="2" :x-gap="28">
            <n-gi span="1" style="margin-bottom: 16px">
              <n-form-item label="机构名称：" path="setOrgName">
                <n-input v-model:value="setOrg.orgName" maxlength="255" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="机构代码：">
                <n-input disabled v-model:value="setOrg.code" maxlength="20"/>
              </n-form-item>
            </n-gi>
            <n-gi span="1" style="margin-bottom: 20px">
              <n-form-item :span="1" label="父级机构" path="parentName">
                <n-select
                  placeholder="选择父级机构"
                  :options="parentNameOptions"
                  v-model:value="setOrg.parentName"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="状态" path="status">
                <n-select
                  placeholder="选择父级机构"
                  :options="statusOptions"
                  v-model:value="setOrg.status"
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item label="备注：">
                <n-input v-model:value="setOrg.remark" maxlength="100"/>
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button
              type="info"
              :loading="formBtnLoading"
              @click="editFrom"
              style="background-color: #2d8cf0; color: #fff"
              >确定</n-button
            >
            <n-button @click="() => (editModal = false)">取消</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 查看操作 -->
    <n-modal :show="viewModal">
      <n-card style="width: 1000px" title="机构详情" size="huge" :bordered="false">
        <n-form
          :label-width="80"
          size="medium"
          ref="formRef"
          :model="viewMenu"
          label-placement="left"
          label-align="left"
        >
          <n-grid :cols="2" :x-gap="28">
            <n-gi span="1" style="margin-bottom: 16px">
              <n-form-item :span="1" label="机构名称" path="orgName">
                <n-input placeholder="机构名称" disabled v-model:value="viewMenu.orgName" />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="机构代码" path="code">
                <n-input placeholder="机构代码" disabled v-model:value="viewMenu.code" />
              </n-form-item>
            </n-gi>
            <n-gi span="1" style="margin-bottom: 20px">
              <n-form-item :span="1" label="父级机构" path="parentName">
                <n-select
                  placeholder="选择父级机构"
                  :options="parentNameOptions"
                  v-model:value="viewMenu.parentName"
                  disabled
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="状态" path="status">
                <n-select
                  placeholder="选择父级机构"
                  :options="statusOptions"
                  v-model:value="viewMenu.status"
                  disabled
                />
              </n-form-item>
            </n-gi>
            <n-gi span="1">
              <n-form-item :span="1" label="描述" path="remark">
                <n-input placeholder="机构描述" disabled v-model:value="viewMenu.remark" />
              </n-form-item>
            </n-gi>
          </n-grid>
        </n-form>
        <template #action>
          <n-space justify="end">
            <n-button
              @click="() => (viewModal = false)"
              style="background-color: #2d8cf0; color: #fff"
              >确认</n-button
            >
          </n-space>
        </template>
      </n-card>
    </n-modal>
    <!-- 删除操作 -->
    <n-modal
      v-model:show="delModal"
      :mask-closable="false"
      preset="dialog"
      title="确认"
      @positive-click="deletConfirm"
      @negative-click="deletCancel"
    >
      <h3 style="font-size: 15px; margin-top: 10px; margin-bottom: 10px">你确定要删除这个机构吗</h3>
      <n-space justify="end">
        <n-button @click="deletConfirm" style="background-color: #2d8cf0; color: #fff"
          >确认</n-button
        >
        <n-button @click="deletCancel">取消</n-button>
      </n-space>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, h, reactive, ref } from 'vue';
import { useMessage } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, useForm } from '@/components/Formdraw/index';
import { PlusOutlined } from '@vicons/antd';
import { useRouter } from 'vue-router';
import { getOrgList } from '@/api/org/list';
import { addOrgInfo } from '@/api/org/add';
import { deleteOrgInfo } from '@/api/org/delete';
import { updateOrgInfo } from '@/api/org/update';
import { viewOrgInfo } from '@/api/org/view';
import formatDate from '@/utils/timestamp';
import { createStorage } from '@/utils/Storage';
const Storage = createStorage({ storage: localStorage });

let authorityJson = Storage.get('OPERATORLIST');
const authority = JSON.parse(authorityJson)

// 表单查询按钮
function handleSubmit(values: Recordable) {
  reloadTable();
}

// 表单重置按钮
function handleReset(values: Recordable) {
  orgListParm.value.orgName = '';
  orgListParm.value.status = '';
  reloadTable();
}

const orgListParm = ref({
  orgName: '',
  status: '',
  pageNum: 1,
  pageSize: 10,
});

// 全体角色列表
const loadDataTable = async (res) => {
  console.log(res);
  orgListParm.value.pageNum = res.page;
  orgListParm.value.pageSize = res.pageSize;
  let data = await getOrgList(orgListParm.value);
  data.data.body.list.forEach((val) => {
    val.createdTime = formatDate(new Date(val.createdTime));
    if (val.status == '0') {
      val.status = '启用';
    } else {
      val.status = '禁用';
    }
  });
  let datas = {
    list: data.data.body.list,
    page: res.page,
    pageSize: res.pageSize,
    pageCount: Math.ceil(data.data.body.total / res.pageSize),
  };
  console.log(data);
  console.log(datas);
  return datas;
};

// 查看-机构状态
const orgStatus = [
  {
    label: '启用',
    value: 0,
  },
  {
    label: '冻结',
    value: 1,
  },
];

// 编辑-机构状态
const statusOptions = [
  {
    label: '启用',
    value: 0,
  },
  {
    label: '禁用',
    value: 1,
  },
];

// 编辑-父机构
const parentNameOptions = [
  {
    label: '机构1',
    value: 0,
  },
  {
    label: '机构2',
    value: 1,
  },
];

// 编辑-默认机构状态
const status = ref('启用');

// 编辑-选择机构状态回调
const handleSelect = (key) => {
  message.info(key);
  status.value = key;
};

// 编辑-默认父机构状态
const parent = ref('机构1');

// 编辑-选择父机构回调
const setParent = (key) => {
  message.info(key);
  parent.value = key;
};

const setOrg = ref({
  orgName: '',
  code: '',
  status: '',
  remark: '',
  parentName: '',
});

// 点击编辑按钮
async function editInfo(record: Recordable) {
  let orgId = record.orgId;
  let data = await viewOrgInfo({ orgId });
  console.log(data);
  setOrg.value = data.data.body;
  if (setOrg.value.status == '0') {
    setOrg.value.status = '启用'
  }
  if (setOrg.value.status == '1') {
    setOrg.value.status = '禁用'
  }
  console.log('点击了编辑', record);
  message.info('点击了编辑');
  editModal.value = true;
}

// 编辑确认按钮
async function editFrom() {
  if (setOrg.value.status == '启用') {
    setOrg.value.status = '0'
  }
  if (setOrg.value.status == '禁用') {
    setOrg.value.status = '1'
  }
  let data = await updateOrgInfo(setOrg.value).then((res) => {
    console.log(res);
    message.success('添加成功');
    reloadTable();
    editModal.value = false;
  });
}
// 表头
const columns = [
  {
    title: '机构ID',
    key: 'orgId',
    width: 120,
  },
  {
    title: '机构名称',
    key: 'orgName',
    width: 120,
  },
  {
    title: '机构代码',
    key: 'code',
    width: 120,
  },
  {
    title: '状态',
    key: 'status',
    width: 120,
  },
  {
    title: '创建时间',
    key: 'createdTime',
    width: 120,
  },
];

const assignModal = ref(false);
const viewModal = ref(false);
const editModal = ref(false);
const router = useRouter();
const addModal = ref(false);
const formRef = ref();
const message = useMessage();
const actionRef = ref();
const roleName = ref();
const roleState = ref();
const delModal = ref(false);
const formBtnLoading = ref(false);
console.log(authority);

// 列表行为
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '查看',
          text: true,
          color: '#2d8cf0',
          onClick: viewInfo.bind(null, record),
          ifShow: () => {
            return authority.includes("org_view");
          },
        },
        {
          label: '编辑',
          text: true,
          color: '#2d8cf0',
          onClick: editInfo.bind(null, record),
          ifShow: () => {
            return authority.includes("org_update");
          },
        },
        {
          label: '删除',
          text: true,
          color: '#ff4949',
          onClick: deletInfo.bind(null, record),
          ifShow: () => {
            return authority.includes("org_delete");
          },
        },
      ],
      select: (key) => {
        message.info(`您点击了，${key} 按钮`);
      },
    });
  },
});

// 表单输入框和表单验证
const schemas = [
  {
    field: 'roleName',
    component: 'NInput',
    label: '机构名称：',
    componentProps: {
      maxlength:"25",
      placeholder: '请输入机构名称',
      onInput: (e: any) => {
        orgListParm.value.orgName = e;
        console.log(e);
      },
    },
  },
  {
    field: 'type',
    component: 'NSelect',
    label: '机构状态：',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        {
          label: '启用',
          value: '0',
        },
        {
          label: '禁用',
          value: '1',
        },
      ],
      onUpdateValue: (e: any) => {
        console.log(e);
        orgListParm.value.status = e;
      },
    },
  },
];

const [register, {}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

// 添加角色信息
function addInfo(record: Recordable) {
  console.log('点击了添加', record);
  message.info('点击了添加');
  addModal.value = true;
}

// 添机构变为响应式
const addRoleMsg = ref({
  orgName: '',
  code: '',
  status: '',
  remark: '',
  parentName: '',
});

//添加机构验证
const addOrg = {
  orgName: {
    required: true,
    message: '请输入机构名称',
    trigger: 'blur',
  },
  code: {
    required: true,
    message: '请输入机构代码',
    trigger: 'blur',
  },
  remark: {
    required: true,
    message: '请输入机构描述',
    trigger: 'blur',
  },
};

// 确认按钮
const addFrom = async (e) => {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      console.log(addRoleMsg.value);
      const roleList = await addOrgInfo(addRoleMsg.value).then((res) => {
        message.success('添加成功');
        reloadTable();
      });
      addModal.value = false;
    } else {
      message.error('添加失败');
    }
  });
};

// 测试查看
const viewOrgRef = ref({
  orgId: 1,
});
async function view(record: Recordable) {
  let data = await viewOrgInfo(viewOrgRef.value);
  console.log(data);
  message.info('查询');
}

// 查看角色信息
const viewMenu = ref({});
async function viewInfo(record: Recordable) {
  let orgId = record.orgId;
  let data = await viewOrgInfo({ orgId });
  viewMenu.value = data.data.body;
  if (viewMenu.value.status == '0') {
    viewMenu.value.status = '启用'
  }
  if (viewMenu.value.status == '1') {
    viewMenu.value.status = '禁用'
  }
  message.info('点击了查看');
  viewModal.value = true;
}

// 删除操作
function deletInfo(record: Recordable) {
  console.log('点击了删除', record);
  localStorage.setItem('record', JSON.stringify(record));
  message.info('点击了删除');
  delModal.value = true;
}

// 确认删除
async function deletConfirm() {
  const deleteRole = JSON.parse(localStorage.getItem('record'));
  console.log(deleteRole);
  let { orgId } = deleteRole;
  let data = await deleteOrgInfo({ orgId });
  console.log(data);
  message.success('删除成功');
  delModal.value = false;
  reloadTable();
}

// 取消删除
function deletCancel() {
  message.success('未删除');
  delModal.value = false;
}

function reloadTable() {
  actionRef.value.reload();
}
</script>

<style lang="less" scoped>
.fromCard {
  margin-top: 12px;
  border: 1px solid rgb(226, 229, 229);
  margin-bottom: 8px;
}
.tableCard {
  border: 1px solid rgb(226, 229, 229);
}
</style>

